package com.stars.empoly.utils

import android.util.Log
import com.stars.empoly.R
import com.stars.empoly.inte.OnCall
import com.stars.empoly.inte.OnUploadCallback
import com.stars.empoly.model.ImageSign
import com.stars.empoly.model.bean.UpImgBean
import com.stars.empoly.utils.net.NetEngine
import com.tencent.mmkv.MMKV
import com.trailer.base.base.BApp
import com.trailer.base.base.BViewModel
import com.trailer.base.dialog.QMUIProgressDialog
import com.trailer.base.view.BView
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import okhttp3.Call
import org.json.JSONObject
import java.io.File
import java.util.*
import java.util.regex.Pattern

/**
 *
 *on 2020/9/16
 */
class OssUtils(var bView: BView, val vm: BViewModel<*>) {

    /**
     * 获取sign
     *
     * @param onCall
     */
    fun getSign(type: String, onCall: OnCall<ImageSign>) {

        vm.repository().rxLreq(NetEngine.service.getSignedUrl(type))
            .doOnNext() {
                onCall.onCall(it.data()!!)
            }.subscribe()
    }

    /**
     * url中是否含有中文
     *
     * @param str
     * @return
     */
    fun isContainChinese(str: String?): Boolean {
        val p = Pattern.compile("[\u4e00-\u9fa5]")
        val m = p.matcher(str)
        return m.find()
    }


    fun setUpLoad(
        type: String,
        urls: ArrayList<String>,
        onUploadListener: OnUploadCallback<UpImgBean>
    ) {

        val size = intArrayOf(urls.size)
        if (size[0] <= 0) return


        val qmuiProgressDialog = arrayOfNulls<QMUIProgressDialog>(1)
        qmuiProgressDialog[0] = QMUIProgressDialog()
        if (null != bView?.context()) {
            qmuiProgressDialog[0]!!.show(bView!!.context())
        }

        for (i in urls.indices) {
            val index = urls[i].lastIndexOf("/")
            var name: String //文件名字不能含有中文
            name = if (isContainChinese(urls[i].substring(index + 1))) {
                System.currentTimeMillis().toString() + ".jpg"
            } else {
                urls[i].substring(index + 1)
            }

            val fileName = name //文件名


            val requestCall = OkHttpUtils.post()
                .url(BApp.instance()!!.config()!!.baseUrl() + "app/upload")
                .addFile("file", fileName, File(urls[i]))
                .id(i)
                .build()

            requestCall.execute(object : StringCallback() {
                override fun onError(call: Call, e: Exception, id: Int) {
                    bView.toast(bView.getStr(R.string.upload_pic_fail) + e)
                    Log.e("-shy-", "onError: $e")
                    size[0]--
                    if (size[0] <= 0) {
                        if (null != bView?.context()) {
                            qmuiProgressDialog[0]!!.dismiss()
                        }
                    }
                }

                override fun onResponse(response: String, id: Int) {
                    //地址
                    var jsonObject = JSONObject(response)
                    val code = jsonObject.optInt("status")
                    var data= jsonObject.optString("data")
                    var jsonObjectTo = JSONObject(data)

                    val url = jsonObjectTo.optString("url")//不完整路径

                    if(code==200){
                        var bean= UpImgBean(-1,url,url)
                        onUploadListener.onUploadSuccess(bean)

                    }
                    size[0]--
                    if (size[0] <= 0) {
                        if (null != bView?.context()) {
                            qmuiProgressDialog[0]!!.dismiss()
                        }
                    }
                }
            })
        }


    }

    var key = ""
    fun setUpLoadMore(
        type: String,
        urls: ArrayList<String>,
        position: Int,
        onUploadListener: OnUploadCallback<UpImgBean>
    ) {
        key = ""
        val size = intArrayOf(urls.size)
        if (size[0] <= 0) return


        for (i in urls.indices) {
            val index = urls[i].lastIndexOf("/")
            var name: String //文件名字不能含有中文
            name = if (isContainChinese(urls[i].substring(index + 1))) {
                System.currentTimeMillis().toString() + ".jpg"
            } else {
                urls[i].substring(index + 1)
            }
            //不能含有空格
            if (isKongGe(name)) {
                name = System.currentTimeMillis().toString() + ".jpg"
            }
            if (name.length > 20) {
                name = System.currentTimeMillis().toString() + ".jpg"
            }


            val fileName = name //文件名


            val requestCall = OkHttpUtils.post()
                .url(BApp.instance()!!.config()!!.baseUrl() + "api/index/upload")
                .addFile("image", fileName, File(urls[i]))
                .addHeader("token", MMKV.defaultMMKV().decodeString("token", ""))
                .id(i)
                .build()
            requestCall.execute(object : StringCallback() {
                override fun onError(call: Call, e: Exception, id: Int) {
                    bView.toast(bView.getStr(R.string.upload_pic_fail) + e)
                    Log.e("-shy-", "onError: $e")
                    size[0]--
                    if (size[0] <= 0) {
                    }
                }

                override fun onResponse(response: String, id: Int) {
                    //地址

                    var jsonObject = JSONObject(response)
                    val code = jsonObject.optInt("code")
                    var data = jsonObject.optString("data")
                    var jsonObjectTo = JSONObject(data)

                    val path = jsonObjectTo.optString("path")//不完整路径

                    val full_path = jsonObjectTo.optString("full_path")//完整路径

                    if (code == 1) {


                        var bean = UpImgBean(position, full_path, path)
                        onUploadListener.onUploadSuccess(bean)

                    }


                    size[0]--
                    if (size[0] <= 0) {

                    }
                }
            })
        }


    }


    fun isKongGe(str: String): Boolean {
        val pattern = Pattern.compile("[\\s]+")
        val matcher = pattern.matcher(str)
        var flag = false
        while (matcher.find()) {
            flag = true
        }

        return flag
    }


}
